const { ipcMain } = require("electron");
const WebSocket = require("ws");


const usersMap = new Map();

// 广播在线用户列表给所有客户端
function broadcastUserList(server) {
  const onlineUsers = Array.from(usersMap.keys());
  server.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify({
        type: 'userList',
        users: onlineUsers
      }));
    }
  });
}

// 广播消息给所有客户端 包含自己
function broadcastMessage(server, message) {
  server.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(message));
    }
  });
}
// 广播消息给所有客户端 不包含自己
function broadcastMessageNoMe(server, message) {
  server.clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN && client.socketIdxos !== message.id) {
      client.send(JSON.stringify(message));
    }
  });
}

// 删除用户
function deleteUser(server, id) {
  usersMap.delete(id);
  broadcastUserList(server);
}

const createServers = {
  start: function (mainWindow) {
    const server = new WebSocket.Server({ port: 9000 });

    function heartbeat() {
      this.isAlive = true;
    }

    server.on("connection", (ws, req) => {
      ws.isAlive = true;
      ws.on("pong", heartbeat);
      console.log("New client connected");

      //on message
      ws.on("message", (message) => {
        console.log(`Received: ${message}`);
        const data = JSON.parse(message);
        // 如果是登录消息，检查用户ID是否已存在
        if (data.login) {
          if (usersMap.has(data.id)) {
            // ID已存在,发送错误消息并关闭连接
            ws.send(JSON.stringify({
              type: 'error',
              message: '该ID已被使用,请更换其他ID'
            }));
            ws.close();
            return;
          }
          // ID不存在,允许登录
          ws.socketIdxos = data.id;
          usersMap.set(data.id, ws);
          // 将 Map 转换为数组形式,只包含用户 ID
          const userList = Array.from(usersMap.keys());
          mainWindow.webContents.send('ws-user-list', userList);
          // 广播更新后的用户列表
          broadcastUserList(server);
        }
        else if (data.type === 'all') {
          broadcastMessage(server, data);
        }
        else if (data.type === 'allNoMe') {
          broadcastMessageNoMe(server, data);
        } else {
          server.clients.forEach(s => {
            if (s.socketIdxos === data.to && s.readyState == 1) {
              s.send(JSON.stringify({ message: data.message }));
            }
          })
        }
      });

      ws.send(JSON.stringify("Welcome to WebSocket server!"));

      ipcMain.on('deleteUser', (event, id) => {
        console.log('删除用户:', id);
        
        if (usersMap.has(id)) {
          const ws = usersMap.get(id);
          // 发送拒绝重连消息
          ws.send(JSON.stringify({
            type: 'error',
            message: '您已被管理员移除,已退出连接'
          }));

          usersMap.delete(id); // 从Map中删除
          
          ws.close(); // 关闭连接
          // 更新用户列表
          const userList = Array.from(usersMap.keys());
          mainWindow.webContents.send('ws-user-list', userList);
          
          // 广播更新后的用户列表
          broadcastUserList(server);
        }
      })
      const interval = setInterval(function ping() {
        server.clients.forEach(function each(ws) {
          if (ws.isAlive === false) return ws.terminate();

          ws.isAlive = false;
          ws.ping();
        });
      }, 30000);

      //on close
      ws.on("close", () => {
        clearInterval(interval);
        // 删除断开连接的用户
        for (let [id, socket] of usersMap.entries()) {
          if (socket === ws) {
            usersMap.delete(id);
            break;
          }
        }
        // 广播更新后的用户列表
        broadcastUserList(server);
        const userList = Array.from(usersMap.keys());
        mainWindow.webContents.send('ws-user-list', userList);
        console.log("Client disconnected");
      });
    });
    console.log("WebSocket server is running on ws://localhost:9000");
    server.listen(9000);
  },
};
module.exports = createServers;
